package org.deltaset.meta.internal;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.deltaset.meta.EntityResolver;

/**
 *
 * @author dmakariev
 */
enum MetaFieldType {

    ENUM,
    ENTITY,
    COLLECTION,
    NUMBER,
    STRING,
    BOOLEAN,
    DATE,
    CUSTOM;
    //UNSUPPORTED;

    static MetaFieldType fromString(String value) {
        try {
            return MetaFieldType.valueOf(value.toUpperCase());
        } catch (IllegalArgumentException ex) {
            return CUSTOM;
        }
    }

    static MetaFieldType mapField(final BeanProperty beanProperty, final EntityResolver entityResolver) {
        final Class originalType = beanProperty.getFieldType();
        if (originalType.isEnum()) {
            return ENUM;
        } else if (entityResolver.isEntity(originalType)) {
            return ENTITY;
        } else if (isCollection(beanProperty)) {
            return COLLECTION;
        }
        final MetaFieldType resolvedType = simpleMap.get(originalType);
        return null != resolvedType ? resolvedType : CUSTOM;
    }

    static MetaFieldType mapParameter(final Class originalType, final EntityResolver entityResolver) {
        final boolean isEntityClass = entityResolver.isEntity(originalType);//(null != originalType.getAnnotation(Entity.class));
        if (originalType.isEnum()) {
            return ENUM;
        } else if (isEntityClass) {
            return ENTITY;
        }
        final MetaFieldType resolvedType = simpleMap.get(originalType);
        return null != resolvedType ? resolvedType : CUSTOM;
    }
    private static final Map<Class, MetaFieldType> simpleMap;

    static {
        simpleMap = new HashMap<Class, MetaFieldType>();
        simpleMap.put(int.class, NUMBER);
        simpleMap.put(Integer.class, NUMBER);
        simpleMap.put(long.class, NUMBER);
        simpleMap.put(Long.class, NUMBER);
        simpleMap.put(float.class, NUMBER);
        simpleMap.put(Float.class, NUMBER);
        simpleMap.put(double.class, NUMBER);
        simpleMap.put(Double.class, NUMBER);
        simpleMap.put(short.class, NUMBER);
        simpleMap.put(Short.class, NUMBER);
        simpleMap.put(byte.class, NUMBER);
        simpleMap.put(Byte.class, NUMBER);
        ///////
        simpleMap.put(String.class, STRING);
        ///////
        simpleMap.put(boolean.class, BOOLEAN);
        simpleMap.put(Boolean.class, BOOLEAN);
        ///////
        simpleMap.put(java.util.Date.class, DATE);

    }

    private static boolean isCollection(final BeanProperty beanProperty) {
        final Class fieldType = beanProperty.getFieldType();
        final boolean isCollection = Collection.class.isAssignableFrom(fieldType);

        return isCollection;
    }
}
